package com.huaxindata.im.model.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.contact.ContactTmp;
import com.huaxindata.im.util.Log;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2017/8/16.
 * 该类是用于本地存储联系人，如果网络请求失败则从本地获取数据
 * 使用标记是否在消息界面用于显示联系人记录
 */

public class ContactStore {

    public static final String TAG = "ContactStore";

    public static final  String DB_NAME    = "history_contact.db";
    public static final  int    VERSION    = 1;
    private final static String TABLE_NAME = "recent_contact";

    private static ContactSqliteHelper sContactSqliteHelper;
    private static SQLiteDatabase      sDatabase;

    public static void init(Context context) {
        if (sContactSqliteHelper == null) {
            sContactSqliteHelper = new ContactSqliteHelper(context, DB_NAME, null, VERSION);
        }
        if (sDatabase == null) {
            sDatabase = sContactSqliteHelper.getWritableDatabase();
        }
    }

    /**
     * 插入一个联系人记录，并记录关系，默认是0陌生人，1是好友2是群
     * 陌生人插入的时候当作ContactPerson对象，一般是在请求添加好友的时候会出现
     */
    public static void insert(Contact contact, int relation,long timestamp) {
        Log.e("lwjing","更新最近联系人");
        ContentValues values = new ContentValues();
        values.put(ContactSqliteHelper.CLIENT_ID, contact.getClientId());
        values.put(ContactSqliteHelper.NICK_NAME, contact.getNickName());
        values.put(ContactSqliteHelper.ICON, contact.getIcon());
        values.put(ContactSqliteHelper.PHONE, contact.getPhone());
        values.put(ContactSqliteHelper.TITLE_NAME, contact.getDuty());
        values.put(ContactSqliteHelper.COMPANY, contact.getCompany());
        values.put(ContactSqliteHelper.CHAT_COUNT, 1);
        values.put(ContactSqliteHelper.SHOW_HISTORY, 0);
        values.put(ContactSqliteHelper.TIMESTAMP,timestamp+"");
        if (contact instanceof ContactPerson) {
            values.put(ContactSqliteHelper.RELATION, relation);
        } else if (contact instanceof ContactGroup) {
            //是群的话就不判断关系了
            values.put(ContactSqliteHelper.RELATION, 2);
        } else if (contact instanceof ContactTmp) {
            values.put(ContactSqliteHelper.RELATION, relation);
        } else {
            //这里return是因为避免不能插入的对象造成异常
            return;
        }
        //5是主键冲突解决方法，选项是一个数组
        // "", " OR ROLLBACK ", " OR ABORT ", " OR FAIL ", " OR IGNORE ", " OR REPLACE "
        sDatabase.insertWithOnConflict(TABLE_NAME, null, values, 5);
    }

    /**
     * 更新字段，是否显示某个联系人的聊天记录
     * 0显示，1不显示，所认默认都是显示的，如果想要
     * 不显示则手动更新数据库中的字段
     */
    public static void updateShow(String clientId, int isShow) {
        String where = ContactSqliteHelper.CLIENT_ID + "=?";
        ContentValues values = new ContentValues(isShow);
        values.put(ContactSqliteHelper.SHOW_HISTORY, isShow);
        sDatabase.update(TABLE_NAME, values, where, new String[]{clientId});
    }

    /**
     * 可以将陌生人转换成好友或群
     * 0是陌生人，1是好友，2是群
     */
    public static void updateRelation(String clientId, int reletion) {
        String sql = "update " + TABLE_NAME + " set " +
                ContactSqliteHelper.RELATION + "=? " +
                " where " + ContactSqliteHelper.CLIENT_ID + "=?;";
        sDatabase.execSQL(sql, new Object[]{reletion, clientId});
    }

    /**
     * 更新与某联系人联系的次数，这需要先查询然后再更新，有
     * 点麻烦，有没有让其查询之前自动增加的方法呢？待实现
     * 先查询聊天次数后更新
     *
     * @param clientId
     */
    public static void updateChatCount(String clientId) {
        //        String sql="select count(client_id) from "+TABLE_NAME+" where client_id="+clientId+";";

    }

    /**
     * 根据id删除一条记录，不管是联系人的还是群的
     *
     * @param clientId:记录的联系人的id
     */
    public static void delete(String clientId) {
        int rows = sDatabase.delete(TABLE_NAME, ContactSqliteHelper.CLIENT_ID + "=?", new String[]{clientId});
        Log.e("lwjing","delet recentcount="+rows);
    }

    /**
     * 查询最近经常联系的联系人，以聊天过的次数为准
     * 聊天的次数在进入聊天页面的时候更新,默认聊天次数大于0
     * 的按降序排序，取前面10个联系次数最多的
     *
     * @return
     */
    public static List<ContactPerson> queryRecentContact() {
        String[] culumn = new String[]{
                ContactSqliteHelper.CLIENT_ID,
                ContactSqliteHelper.NICK_NAME,
                ContactSqliteHelper.ICON,
                ContactSqliteHelper.RELATION,
                ContactSqliteHelper.PHONE,
                ContactSqliteHelper.TITLE_NAME,
                ContactSqliteHelper.COMPANY
        };
        String selection = ContactSqliteHelper.CHAT_COUNT + ">=?";
        List<ContactPerson> list = new ArrayList<>();
        Cursor cursor = sDatabase.query(TABLE_NAME, culumn, selection, new String[]{"0"},
                null, null, ContactSqliteHelper.CHAT_COUNT + " desc", "10");
        //以下部分生成联系人对象
        while (cursor.moveToNext()) {
            int relation = cursor.getInt(cursor.getColumnIndex(ContactSqliteHelper.RELATION));
            String clientId = cursor.getString(cursor.getColumnIndex(ContactSqliteHelper.CLIENT_ID));
            String nickName = cursor.getString(cursor.getColumnIndex(ContactSqliteHelper.NICK_NAME));
            String icon = cursor.getString(cursor.getColumnIndex(ContactSqliteHelper.ICON));
            String phone = cursor.getString(cursor.getColumnIndex(ContactSqliteHelper.PHONE));

            String titleName = cursor.getString(cursor.getColumnIndex(ContactSqliteHelper.TITLE_NAME));
            String company = cursor.getString(cursor.getColumnIndex(ContactSqliteHelper.COMPANY));

            if (relation == 1) {//好友
                ContactPerson person = new ContactPerson(clientId, icon, nickName, phone, titleName, company);
                list.add(person);
            }
        }
        return list;
    }

    /**
     * 查询所有需要显示消息记录的联系人
     * 0显示，1不显示
     */
    public static List<Contact> queryAllContact() {
        String[] culumns = new String[]{
                ContactSqliteHelper.CLIENT_ID,
                ContactSqliteHelper.NICK_NAME,
                ContactSqliteHelper.ICON,
                ContactSqliteHelper.RELATION,
                ContactSqliteHelper.TIMESTAMP
        };
        List<Contact> list = new ArrayList<>();
        String where = ContactSqliteHelper.SHOW_HISTORY + "=?";
        String orderBy= ContactSqliteHelper.TIMESTAMP +" DESC";
        Cursor cursor = sDatabase.query(TABLE_NAME, culumns, where, new String[]{"0"}, null, null, orderBy);
        //以下部分生成联系人对象
        while (cursor.moveToNext()) {
            int relation = cursor.getInt(3);
            String clientId = cursor.getString(0);
            String nickName = cursor.getString(1);
            String icon = cursor.getString(2);
            //根据不同的关系生成不同的对象
            if (relation == 0) {//陌生人
                ContactTmp contactTmp = new ContactTmp(clientId, nickName, icon);
                list.add(contactTmp);
            } else if (relation == 1) {//好友
                ContactPerson person = new ContactPerson(clientId, nickName, icon);
                list.add(person);
            } else if (relation == 2) {//群
                ContactGroup group = new ContactGroup(clientId, null, nickName, icon);
                list.add(group);
            }
        }
        return list;
    }

    private static class ContactSqliteHelper extends SQLiteOpenHelper {

        //如果是群就对应的是群的信息
        public static final  String CLIENT_ID    = "client_id";//客户端id
        public static final  String NICK_NAME    = "nick_name";//昵称
        public static final  String ICON         = "icon";//头像
        public static final  String PHONE        = "phone";//电话
        //与用户的关系，0是陌生人，1是好友，2是群
        public static final String RELATION     = "relation";
        public static final String CHAT_COUNT   = "chat_count";//聊天次数
        //是否显示在消息记录界面0显示，1不显示
        public static final String SHOW_HISTORY = "show_history";
        //头衔
        public static final String TITLE_NAME   = "title_name";
        //公司
        public static final String COMPANY      = "company";
        //最近一次聊天的时间戳
        public static final String TIMESTAMP    = "timestamp";
        private static      int    VERSION      = 2;

        public ContactSqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory
                factory, int version) {
            super(context, name, factory, VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.e("lwjing","数据库创建成功");
            String sql = "create table " + TABLE_NAME +
                    " (" +
                    CLIENT_ID + " text primary key," +
                    NICK_NAME + " text," +
                    ICON + " text," +
                    PHONE + " text," +
                    TITLE_NAME + " text," +
                    COMPANY + " company," +
                    RELATION + " integer," +
                    CHAT_COUNT + " integer," +
                    SHOW_HISTORY + " integer," +
                    TIMESTAMP + " integer" +
                    " );";
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.e("lwjing", "recent_contact onUpgrade");
            db.execSQL("drop table if exists " + TABLE_NAME + ";");
            onCreate(db);
        }
    }
}
